﻿namespace Mozi.Live.SDP
{
    /// <summary>
    /// 链接地址信息
    /// </summary>
    public class SDPConnection
    {
        private string netType = "IN";
        private uint portCount = 1;
        private string addressType = "IP4";

        /// <summary>
        /// 网络类型 默认为IN-Internet
        /// </summary>
        public string NetType { get => netType; set => netType = value; }
        /// <summary>
        /// 地址类型 IP4-IPV4 IP6-IPV6
        /// </summary>
        public string AddressType { get => addressType; set => addressType = value; }
        /// <summary>
        /// 地址
        /// </summary>
        public string Address { get; set; }
        /// <summary>
        /// 生存时间
        /// </summary>
        public uint TTL { get; set; }
        /// <summary>
        /// 端口数量 可选
        /// </summary>
        public uint PortCount { get => portCount; set => portCount = value; }
        /// <summary>
        /// 转为字符串表达式
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {

            string result = $"{NetType} {AddressType} {Address}";
            if (TTL > 0)
            {
                result += "/" + TTL;
            }
            if (PortCount > 1)
            {
                result += "/" + PortCount;
            }
            return result;
        }
        /// <summary>
        /// 解析字符串 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <remarks>格式 IN IP4 224.2.17.12/127[{portcount}]</remarks>
        public static SDPConnection Parse(string data)
        {
            SDPConnection con = new SDPConnection();
            string[] first = data.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
            con.NetType = first[0];
            con.AddressType = first[1];
            string[] last = first[2].Split(new char[] { '/' }, System.StringSplitOptions.RemoveEmptyEntries);
            con.Address = last[0];
            if (last.Length > 1)
            {
                con.TTL = uint.Parse(last[1]);
            }
            if (last.Length > 2)
            {
                con.PortCount = uint.Parse(last[2]);
            }
            return con;
        }
    }

}
